﻿using System;
using System.Web.Mvc;

namespace Framework.Mvc
{
    /// <summary>
    /// 文件上传的模型绑定
    /// </summary>
    public class FilesUploadedModelBinder : IModelBinder
    {
        static FilesUploadedModelBinder()
        {
            FilesUploadedModelBinderModelName = "filesUploaded";
        }

        public static string FilesUploadedModelBinderModelName;

        public object BindModel(ControllerContext controllerContext, ModelBindingContext bindingContext)
        {
            if (bindingContext.ModelName.Equals(FilesUploadedModelBinderModelName, StringComparison.CurrentCulture))
            {
                var result = bindingContext.ValueProvider.GetValue(FilesUploadedModelBinderModelName);
                if (result != null)
                {
                    FilesUploaded files = new FilesUploaded();
                    var ids = result.AttemptedValue.Split(',');
                    foreach (var id in ids)
                    {
                        Guid guid;
                        if (Guid.TryParse(id, out guid))
                        {
                            files.Identities.Add(guid);
                        }
                    }
                    return files;
                }
            }
            return null;
        }
    }
}